package com.haohan.platform.service.sys.common.persistence;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.haohan.platform.service.sys.common.utils.IdGen;
import com.haohan.platform.service.sys.common.utils.JedisUtils;
import com.haohan.platform.service.sys.modules.pds.constant.IPdsConstant;
import com.haohan.platform.service.sys.modules.sys.entity.User;
import com.haohan.platform.service.sys.modules.sys.utils.UserUtils;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.validator.constraints.Length;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpSession;
import java.lang.reflect.Field;
import java.util.Date;

/**
 * 数据Entity类
 *
 * @author ThinkGem
 * @version 2014-05-16
 */
public abstract class DataEntity<T> extends BaseEntity<T> {

    private static final long serialVersionUID = 1L;

    protected String remarks;    // 备注
    protected User createBy;    // 创建者
    protected Date createDate;    // 创建日期
    protected User updateBy;    // 更新者
    protected Date updateDate;    // 更新日期
    protected String delFlag;    // 删除标记（0：正常；1：删除；2：审核）

    public DataEntity() {
        super();
        this.delFlag = DEL_FLAG_NORMAL;
    }

    public DataEntity(String id) {
        super(id);
    }

    /**
     * 插入之前执行方法，需要手动调用
     */
    @Override
    public void preInsert() {
        User user = UserUtils.getUser();
        if (StringUtils.isNotBlank(user.getId())) {
            this.updateBy = user;
            this.createBy = user;
        }
        // tenant 设置
        Integer tenantId = fetchTenantId(user);
        if (null != tenantId) {
            this.tenantId = tenantId;
        }
        // 不限制ID为UUID，调用setIsNewRecord()使用自定义ID
        if (!this.isNewRecord) {
            // 修改为使用自定义主键生成规则
            // setId(IdGen.uuid());
            setId(IdGen.genByT(getClass()));
        }
        this.updateDate = new Date();
        this.createDate = this.updateDate;
    }

    /**
     * 1.优先从session获取
     * 2.表字段带pmId时可通过pmId和tenantId的缓存映射获取
     * 3.通过当前用户对应的tenantId设置
     *
     * @param user
     * @return
     */
    private Integer fetchTenantId(User user) {
        HttpSession session = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getSession();
        Integer tenantId = (Integer) session.getAttribute(IPdsConstant.TENANT_KEY);
        if (null != tenantId) {
            return tenantId;
        }
        // pmId 获取
        try {
            Field field = getClass().getDeclaredField(IPdsConstant.PM_KEY);
            field.setAccessible(true);
            Object pmId = field.get(this);
            tenantId = Integer.valueOf(JedisUtils.getMap(IPdsConstant.TENANT_MAP_KEY).get(pmId));
            if (null != tenantId) {
                session.setAttribute(IPdsConstant.TENANT_KEY, tenantId);
                return tenantId;
            }
        } catch (Exception e) {
        }
        tenantId = this.tenantId;
        tenantId = (null == tenantId) ? user.getTenantId() : tenantId;
        if (null != tenantId) {
            session.setAttribute(IPdsConstant.TENANT_KEY, tenantId);
        }
        return tenantId;
    }

    /**
     * 更新之前执行方法，需要手动调用
     */
    @Override
    public void preUpdate() {
        User user = UserUtils.getUser();
        if (StringUtils.isNotBlank(user.getId())) {
            this.updateBy = user;
        }
        this.updateDate = new Date();
    }

    @Length(min = 0, max = 2000)
    public String getRemarks() {
        return remarks;
    }

    public void setRemarks(String remarks) {
        this.remarks = remarks;
    }

    @JsonIgnore
    public User getCreateBy() {
        return createBy;
    }

    public void setCreateBy(User createBy) {
        this.createBy = createBy;
    }

    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    public Date getCreateDate() {
        return createDate;
    }

    public void setCreateDate(Date createDate) {
        this.createDate = createDate;
    }

    @JsonIgnore
    public User getUpdateBy() {
        return updateBy;
    }

    public void setUpdateBy(User updateBy) {
        this.updateBy = updateBy;
    }

    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    public Date getUpdateDate() {
        return updateDate;
    }

    public void setUpdateDate(Date updateDate) {
        this.updateDate = updateDate;
    }

    @JsonIgnore
    @Length(min = 1, max = 1)
    public String getDelFlag() {
        return delFlag;
    }

    public void setDelFlag(String delFlag) {
        this.delFlag = delFlag;
    }


}
